let app = null;

// 使用方式：
// 引入: import Login from "./utils/Login.js"
// app.js设置全局:that.xlogin = new Login(that)
// 设置可重新请求: app.xlogin.reLogin()
// 调用:app.xlogin.getUser(function (res) {})

function Init(global) {
  const that = this;
  this.loginStatus = 0; //当前操作状态：0为未登录，1为登录中，2登录成功，-1为code获取失败，-2为授权失败，-3服务器获取用户失败
  this.storageName = "user"; //用户缓存名字
  this.codeObj = {
    code: '',
    codeMsec: '',
  }; //用户获取code相关信息
  this.userInfo = {}; //用户授权相关信息
  this.getUser = getUser; //page判断并获取用户信息
  this.getUserStorage = getUserStorage; //获取本地缓存的用户数据。赋值到app.userInfo中
  this.reLogin = reLogin; //设置可重新加载
  // this.loginCallBack = null; //page获取用户信息完成回调函数
  this.loginCallBacks = [];
  this.handle = handle;
  this.wxLogin = wxLogin; //获取code
  this.getUserInfo = getUserInfo; //获取用户信息
  this.serviceLogin = serviceLogin; //授权登录

  if (global) app = global;
}

function getUser(loginCallBack) {
  if (!app) app = getApp();
  const that = this;
  const userInfo = app.userInfo;
  let userId = userInfo && userInfo.userId || "";

  if (loginCallBack) that.loginCallBacks.push({loginCallBack});
  if (!userId) {

    if (that.loginStatus == 0) {
      that.loginStatus = 1
      that.wxLogin();
    } else if (that.loginStatus == 1) {

    } else {
      // 没有用户信息，并且获取用户信息完毕。表示获取用户失败
      that.handle();
    }
    return false;
  } else {
    that.handle(userInfo);
    return userInfo;
  }
}

function getUserStorage() {
  const that = this;
  let user = app.getStorageSync(that.storageName) || {};
  user.noLogin = true;
  app.userInfo = user;
  return user;
}

function reLogin(loginCallBack) {
  const that = this;
  // if (that.loginStatus == 1) return;
  if (loginCallBack) that.loginCallBacks.push({ loginCallBack });
  that.loginStatus = 1
  that.wxLogin();
}

/**
 * 获取code 
 * @params wrongs Number 请求次数[失败时累加]
 */
function wxLogin(wrongs = 0) {
  const that = this;
  // 需要先调用login再调用getUserInfo，不然会概率性获取用户失败
  app.login({
    success: function(res) {
      const code = res.code;
      console.log("获取code成功", code);
      that.codeObj.code = code;
      that.codeObj.codeMsec = (new Date()).getTime();
      that.getUserInfo();
    },
    fail: function() {
      if (wrongs == 2) {
        that.loginStatus = -1;
        that.handle();
        app.showModal({
          title: '提示',
          showCancel: false,
          content: '当前获取code多次失败，请联系平台管理员',
        })
        return false;
      }
      that.wxLogin(wrongs++);
    }
  })
}

/**
 * 自动获取用户信息，已授权可以
 */
function getUserInfo() {
  const that = this;
  app.getUserInfo({
    complete(res) {
      console.log("获取用户信息", res);
      if (res.encryptedData) {
        that.userInfo = res;
      }
      that.serviceLogin();
    }
  })
}

/**
 * 服务器登录接口
 * @params 用户密钥信息
 */
function serviceLogin() {
  const that = this;
  if (!that.userInfo.encryptedData) {
    console.log("获取用户未授权", that.userInfo);
    that.loginStatus = -2;
    that.handle();
    return;
  }

  const reqData = {
    userSecretData: that.userInfo.encryptedData || '',
    secrectIv: that.userInfo.iv || '',
    wx_code: that.codeObj.code,
    shareUserId: app.shareUserId || '',
    shareActivityUuid: app.shareActivityUuid || '',
    invitorUuid: app.invite.invitorUuid || '',
    activityUuid: app.invite.activityUuid || '',
  }

  app.middleware.requestAjax({
    serAddr: app.serAddrs.login,
    data: reqData,
    cancelToast: true,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      console.log("success获取服务器用户", res);
      that.loginStatus = 2;
      try {
        if (that.userInfo.encryptedData) res.data.noLogin = false;
        app.userInfo = Object.assign({}, app.userInfo || {}, res.data.user || {});
        app.userInfo.plug_token = res.data.token;
        console.log('在登录成功以后，就要把token传进小程序的插件里面了');
        app.plugin.setToken(res.data.token);
        app.plugin.setOpenId(res.data.user.openId);
        console.log("app.userInfo", app.userInfo)
      } catch (e) {
        console.error("问题错", e);
      }
      that.handle(app.userInfo);
    },
    fail: function() {
      that.loginStatus = -3;
      that.handle();
    }
  })
}

function handle(userInfo) {
  const that = this;
  const cb = that.loginCallBacks;
  for (let i = 0; i < cb.length; i++) {
    // 是否已回调过
    if(cb[i].isCall) continue;
    cb[i].isCall = true;
    if (cb[i].loginCallBack) cb[i].loginCallBack(userInfo);
  }
}

export default Init;